package spindles.api.util;

import java.io.File;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import spindles.api.db.DAO;
import spindles.api.domain.Settings;

public class Config {
	
	public static final String PROPERTIES_FILENAME = "spindles.properties";
	
	public static final String defaultDBHome = "db";
	
	public static final String RESOURCES_DIR = "resources";
	
	private Configuration config;
	
	private File baseDir;
	
	private Settings settings;
	
	private static Config instance = new Config();
	
	protected Config() {}
	
	public static void init(String baseDir){
		try {
			instance.baseDir = new File(baseDir);
			File propFile = 
				new File(FilenameUtils.concat(baseDir, PROPERTIES_FILENAME));
			instance.config = new PropertiesConfiguration(propFile);
			
			DAO<Settings> dao = new DAO<Settings>(Settings.class);
			instance.settings = dao.findAllSorted().first();
			
		} catch (ConfigurationException e) {
			throw new ApplicationException(e);
		}
	}
	
	public static void testInit(String baseDir){
		try {
			instance.baseDir = new File(baseDir);
			File propFile = 
				new File(FilenameUtils.concat(baseDir, PROPERTIES_FILENAME));
			instance.config = new PropertiesConfiguration(propFile);		
			
		} catch (ConfigurationException e) {
			throw new ApplicationException(e);
		}
	}
	
	public static File getDBHome(){
		String dbDir = instance.config.getString("db.home", defaultDBHome);
		
		if(dbDir.equals(defaultDBHome)){
			return new File(instance.baseDir, defaultDBHome);
		}
		return new File(
				FilenameUtils.concat(instance.baseDir.getAbsolutePath(), dbDir));
	}
	
	public static String getPlotWidth(){
		return "" + instance.settings.getPlotWidth();
		//return instance.config.getString("plot.width", "1000");
	}
	
	public static String getPlotHeight(){
		return "" + instance.settings.getPlotHeight();
		//return instance.config.getString("plot.height", "700");
	}
	
	public static String getPlotCSS(){
		return instance.config.getString("plot.css", "");
	}
	
	public static String getBptrPath(){
		return FilenameUtils.concat(instance.baseDir.getAbsolutePath(), 
				RESOURCES_DIR + IOUtils.DIR_SEPARATOR + "bptr.mat");
	}
	
//	public static boolean getPlotRaw(){
//		return instance.config.getBoolean("plot.raw", false);
//	}
	
	
	
	

}
